package com.bizmda.bizsip.app.executor;

import cn.hutool.json.JSONObject;
import com.bizmda.bizsip.app.executor.script.MagicScriptHelper;
import com.bizmda.bizsip.common.*;
import lombok.extern.slf4j.Slf4j;
import org.ssssssss.script.MagicScriptContext;

import java.util.Map;

/**
 * @author 史正烨
 */
@Slf4j
public class ScriptAppExecutor extends AbstractAppExecutor {
    private String content;


    public ScriptAppExecutor(String serviceId, String type, Map configMap) {
        super(serviceId, type, configMap);
        this.content = (String) configMap.get("script");
        log.trace("初始化script脚本App服务[{}]:\n{}",serviceId,this.content);

    }

    @Override
    public void init() {
        // 没有初始化内容
    }

    @Override
    public BizMessage<JSONObject> doAppService(BizMessage inBizMessage) throws BizException {
        log.trace("调用script脚本类App服务[{}]请求报文:\n{}",this.serviceId,BizUtils.buildBizMessageLog(inBizMessage));
        MagicScriptContext context = new MagicScriptContext();
        context.set("bizmessage", inBizMessage);
        log.trace("App服务[{}]script脚本:\n{}",this.serviceId,this.content);
        Object result = MagicScriptHelper.executeScript(this.content, context);
        if (result instanceof ExecutorError) {
            if (((ExecutorError)result).isTimeoutException()) {
                log.warn("sip.timeout():{}", ((ExecutorError) result).getMessage());
                throw new BizException(BizResultEnum.RETRY_DELAY_APP_SERVICE,((ExecutorError) result).getMessage());
            }
            else {
                log.warn("sip.error():{}", ((ExecutorError) result).getMessage());
                throw new BizException(BizResultEnum.INTEGRATOR_SCRIPT_RETURN_EXECUTOR_ERROR, ((ExecutorError) result).getMessage());
            }
        }

        BizMessage<JSONObject> result1 = BizTools.buildJsonObjectMessage(inBizMessage,result);
        log.trace("script脚本类App服务响应报文:\n{}",BizUtils.buildBizMessageLog(result1));
        return result1;
    }

}
